<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>
        <img id="avatarImg" style="width:100px;height:100px" alt="">
        <label for="#file">上传头像:</label><input type="file" id="file">
    </div>
    <div>
        <label for="#username">用户名:</label><input type="text" id="username">
    </div>
    <div>
        <label for="#password">密码:</label><input type="password" id="password">
    </div>
    <button id="btn">提交</button>
    <script>
        /*
            1.通过input[type=file]标签,实现弹窗选择文件功能
            2.给input绑定change事件回调函数,监听用户选择文件操作
            3.在change事件中,可以通过this.files获取到用户引入的文件数据
            4.创建FormData对象,将当前文件数据append进入该对象
            5.将FprmData对象作为请求体body发送给服务器
        */
        let formdata= new FormData();

        //当用户选择图片时,自动上传
        file.onchange=async function(){
            console.log(this.files[0])
            const image =this.files[0];
            formdata.append('file',image);
            console.log('formdata',formdata);
            let result = await axios.post('http://localhost:3000/upload',formdata);
            avatarImg.src="http://localhost:3000"+result.data;
            // const img= new Image();
            // img.src="http://localhost:3000"+result.data;
            // img.width="100";
            // img.height="100";
            // avatarImg.appendChild(img)
        }

        //当用户点击提交按钮时,收集用户数据,并发送请求
        btn.onclick=async function(){
            //收集用户数据
            let usernameValue = username.value.trim();
            let passwordValue = password.value.trim();
            let avatarSrc = avatarImg.src;

            //数据校验->前端表单验证
            if(usernameValue&&passwordValue&&avatarImg){
                let result = await axios.post('http://localhost:3000/register',{
                    username:usernameValue,
                    password:passwordValue,
                    avatarImg:avatarSrc
                });
                alert(result.data)
            }
        }

    </script>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.0/axios.min.js"></script>
</body>
</html>